package org.kiranputtur.phonebook;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.util.List; 
import javax.swing.JButton;
import javax.swing.Box;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.BoxLayout;
import javax.swing.BorderFactory;
import javax.swing.JOptionPane;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;

/**
 *  @author Kiran Puttur
 *	@category Final Project
 */

public class PhoneBook {

	public static void main(String[] args) {
		
			EventQueue.invokeLater(new Runnable()
			{
				public void run()
				{
					JFrame frame = new PhoneBookFrame();
					frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
					frame.setVisible(true);
				}
			});
		}
}
class PhoneBookFrame extends JFrame
{
	public PhoneBookFrame()
	{
		super("PhoneBook Application by Kiran Puttur");
			
		//createGUI
		entryPanel = new JPanel();
		buttonPanel = new JPanel();
		recLabel = new JLabel();
		recTextField = new JTextField();
		lastNameLabel = new JLabel();
		lastNameTextField = new JTextField();
		firstNameLabel = new JLabel();
		firstNameTextField = new JTextField();
		phoneNumberLabel = new JLabel();
		phoneNumberTextField = new JTextField();
		
		//TextArea for display
		ResultsDisplay = new JTextArea();
		
		//Buttons
		addButton = new JButton();
		updateButton = new JButton();
		findButton = new JButton();
		deleteButton = new JButton();
		clearButton = new JButton();
		exitButton = new JButton();
		
		//border
		Border border = LineBorder.createGrayLineBorder();
		
		//Starting Location and Size
		setLocation(100, 50);
		setSize( 600, 350 );
	      setVisible( true );
		
		
		
		entryPanel.setLayout( new GridLayout(4,2) );
		
		recLabel.setText("Record Number                                  ");
		recLabel.setFont(new Font("Serif", Font.BOLD, 15));
		recLabel.setHorizontalAlignment(JLabel.LEFT);
		recLabel.setBorder(border);
				entryPanel.add(recLabel);
		
		recTextField.setEditable(false);
		entryPanel.add(recTextField);
		
		lastNameLabel.setText("Last Name");
		lastNameLabel.setFont(new Font("Serif", Font.BOLD, 15));
		lastNameLabel.setBorder(border);
		
		entryPanel.add(lastNameLabel);
		
		lastNameTextField.setEditable(true);
		entryPanel.add(lastNameTextField);
		
		firstNameLabel.setText("First Name");
		firstNameLabel.setFont(new Font("Serif", Font.BOLD, 15));
		firstNameLabel.setBorder(border);
		entryPanel.add(firstNameLabel);
		
		firstNameTextField.setEditable(true);
		entryPanel.add(firstNameTextField);
		
		phoneNumberLabel.setText("Phone Number");
		phoneNumberLabel.setFont(new Font("Serif", Font.BOLD, 15));
		phoneNumberLabel.setBorder(border);
		entryPanel.add(phoneNumberLabel);
		
		phoneNumberTextField.setEditable(true);
		entryPanel.add(phoneNumberTextField);
		
		 getContentPane().add( entryPanel, BorderLayout.NORTH );
		
		 //Let have the Black border Like professor's demo 
		 Border blackline = BorderFactory.createMatteBorder(4,1,4,1,Color.black);

		
		ResultsDisplay.setEditable(true);
		ResultsDisplay.setBorder(blackline);
		JScrollPane scrollPane = new JScrollPane(ResultsDisplay,
                JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
		
		getContentPane().add( scrollPane, BorderLayout.CENTER );
		
		//establish database connection and setup prepared statements
	   
		contactQueries = new Queries();
		//Since we cannot come here unless database connection is successfull.
		ResultsDisplay.append("Database Connection Successfull!" + "\n");
	   
	   
		
		
		//Lets set all the buttons
		buttonPanel.setLayout(new GridLayout(2,3));
		
		addButton.setText("Add Contact");
		addButton.addActionListener(new ActionListener()
		         {
		            public void actionPerformed( ActionEvent evt )
		            {
		               addButtonActionPerformed( evt );
		            } // end method actionPerformed
		         } // end anonymous inner class
		      ); // end call to addActionListener
		
		buttonPanel.add(addButton);
		
		updateButton.setText("UpdateContact");
		buttonPanel.add(updateButton);
		updateButton.addActionListener(
        new ActionListener()
        {
           public void actionPerformed( ActionEvent evt )
           {
              updateButtonActionPerformed( evt );
           } // end method actionPerformed
        } // end anonymous inner class
     ); // end call to updateActionListener
		
		
		findButton.setText("Find Contact");
		buttonPanel.add(findButton);
		findButton.addActionListener(
		new ActionListener()
		{
			public void actionPerformed( ActionEvent evt)
			{
				findButtonActionPerformed( evt,1 );
			} //end method action Performed
		} // end annonymous inner class
		); //end call to findActionListener
		
		
		deleteButton.setText("Delete Contact");
		buttonPanel.add(deleteButton);
		deleteButton.addActionListener(
				new ActionListener()
				{
					public void actionPerformed( ActionEvent evt)
					{
						deleteButtonActionPerformed( evt );
					} // end method action Performed
				} // end annonymous inner class
				); // end call to deleteActionListener
		
		clearButton.setText("Clear");
		buttonPanel.add(clearButton);
		clearButton.addActionListener(
				new ActionListener()
				{
					public void actionPerformed(ActionEvent evt)
					{
						clearButtonActionPerformed (evt);
					} //end method
				} // end annonymous inner class
	); // end call to clear Button Action Performed
		
		exitButton.setText("Exit");
		buttonPanel.add(exitButton);
		
		exitButton.addActionListener(
				new ActionListener()
				{
					public void actionPerformed(ActionEvent evt)
					{
						contactQueries.close();
						System.exit( 0 );
					}
				});
		
		getContentPane().add(buttonPanel, BorderLayout.SOUTH);
		
		
		addWindowListener( new WindowAdapter() 
		         {  
		            public void windowClosing( WindowEvent evt )
		            {
		               contactQueries.close(); // close database connection
		               System.exit( 0 );
		            } // end method windowClosing
		         } // end anonymous inner class
		      ); // end call to addWindowListener
		
	}

//handles event when Add Button is clicked.
private void addButtonActionPerformed(ActionEvent evt)
{
	//Lets check whether any of the fields are empty or NULL
	if ( firstNameTextField.getText().length() < 1 ||
			lastNameTextField.getText().length() < 1 ||
			phoneNumberTextField.getText().length()< 1)
	{
		JOptionPane.showMessageDialog( this, "Name and Phone required!",
	            "Error", JOptionPane.PLAIN_MESSAGE );
		return; }
	
	int result = contactQueries.addContact(firstNameTextField.getText(),
			lastNameTextField.getText(),phoneNumberTextField.getText());
	
	ResultsDisplay.append("Inserting:INSERT INTO PHONE_BOOK(First,Last,Phone) VALUES('" +
			firstNameTextField.getText() + "';'" + lastNameTextField.getText() +
			"';'" + phoneNumberTextField.getText() + "')" + "\n");
	
	  if ( result == 1 )
	         JOptionPane.showMessageDialog( this, "Contact added!",
	            "Contact added", JOptionPane.PLAIN_MESSAGE );
	      else
	         JOptionPane.showMessageDialog( this, "Contact not added!",
	            "Error", JOptionPane.PLAIN_MESSAGE );
	  findButtonActionPerformed(evt,5);
	  
	  ResultsDisplay.append("Insert Successful" + "\n");
	 }

private void updateButtonActionPerformed(ActionEvent evt)
{
	//check for empty values in these fields
	if ( firstNameTextField.getText().length() < 1 ||
			lastNameTextField.getText().length() < 1 ||
			phoneNumberTextField.getText().length()< 1)
	{
		JOptionPane.showMessageDialog( this, "Name and Phone required!",
	            "Error", JOptionPane.PLAIN_MESSAGE );
		return; }
	
	//lets get the ID through Find contact before we update
	
	currentEntry = new Contact();
	currentEntry = contactQueries.findContacts(firstNameTextField.getText(),
			lastNameTextField.getText());
	//if returned result does not match then fail
	if ( currentEntry.getRecordNumber() < 1)
	{
		JOptionPane.showMessageDialog( this, "No contact found to update!",
	            "Error", JOptionPane.PLAIN_MESSAGE );
		return;
	}
	
	int result = contactQueries.updateContacts(firstNameTextField.getText(),
			lastNameTextField.getText(), phoneNumberTextField.getText(),
			currentEntry.getRecordNumber());
	
	ResultsDisplay.append("Updating:UPDATE PHONE_BOOK SET First='" + firstNameTextField.getText() +
			"';Last='" + lastNameTextField.getText() + "'; Phone='" +
			phoneNumberTextField.getText() + "' WHERE Id=" + currentEntry.getRecordNumber() + "\n");
	
	  if ( result == 1 )
	         JOptionPane.showMessageDialog( this, "Contact Updated",
	            "Contact Updated", JOptionPane.PLAIN_MESSAGE );
	      else
	         JOptionPane.showMessageDialog( this, "Failed to Update!",
	            "Error", JOptionPane.PLAIN_MESSAGE );
	  findButtonActionPerformed(evt,5);
	  
	 ResultsDisplay.append("Update Successful" + "\n");
}


private void findButtonActionPerformed(ActionEvent evt, int num)
{
	if ( num  == 1)
	{
	if ( firstNameTextField.getText().length() < 1 ||
			lastNameTextField.getText().length() < 1)
	{
		JOptionPane.showMessageDialog( this, "Enter First and last Name to search",
	            "INFO", JOptionPane.PLAIN_MESSAGE );
		return; } }
	
	currentEntry = new Contact();
	
	currentEntry = contactQueries.findContacts(firstNameTextField.getText(),
			lastNameTextField.getText());
	
	if ( num == 1)
		ResultsDisplay.append("Sending Query: SELECT * FROM PHONE_BOOK" +
			"WHERE  First='" + firstNameTextField.getText() + "' AND Last='" +
			lastNameTextField.getText() + "'" + "\n");
	
	if ( currentEntry.getRecordNumber() < 1)
			JOptionPane.showMessageDialog( this, "No Such contact found!",
	            "INFO", JOptionPane.PLAIN_MESSAGE );
	else
	{
		recTextField.setText(""+ currentEntry.getRecordNumber());
		firstNameTextField.setText(currentEntry.getFirstName());
		lastNameTextField.setText(currentEntry.getLastName());
		phoneNumberTextField.setText(currentEntry.getPhoneNumber());
		}
	
	if (num == 1)
	ResultsDisplay.append("Find Successful" + "\n");
}

private void deleteButtonActionPerformed(ActionEvent evt)
{
	if ( firstNameTextField.getText().length() < 1 ||
			lastNameTextField.getText().length() < 1)
	{
		JOptionPane.showMessageDialog( this, "Enter First and last Name to search",
	            "INFO", JOptionPane.PLAIN_MESSAGE );
		return;
	}
	
//lets get the ID through Find contact before we delete
	
	currentEntry = new Contact();
	currentEntry = contactQueries.findContacts(firstNameTextField.getText(),
			lastNameTextField.getText());
//	
	if (currentEntry.getRecordNumber() < 1)
	{
		JOptionPane.showMessageDialog( this, "No such contact to delete!",
	            "Error", JOptionPane.PLAIN_MESSAGE );
		return;
	}
	
	int result = contactQueries.deleteContacts(currentEntry.getRecordNumber());
	
	ResultsDisplay.append("Deleting:DELETE from PHONE_BOOK WHERE Id=" +
			currentEntry.getRecordNumber() + "\n");
	  if ( result == 1 )
	         JOptionPane.showMessageDialog( this, "Contact Deleted",
	            "Contact Deleted", JOptionPane.PLAIN_MESSAGE );
	      else
	         JOptionPane.showMessageDialog( this, "Failed to Delete!",
	            "Error", JOptionPane.PLAIN_MESSAGE );
	clearButtonActionPerformed(evt);
	ResultsDisplay.append("Delete Successful" + "\n");
}

private void clearButtonActionPerformed(ActionEvent evt)
{
	SwingUtilities.invokeLater(
			new Runnable()
			{
			   public void run()
			   {
				   recTextField.setText("");
				   lastNameTextField.setText("");
				   firstNameTextField.setText("");
				   phoneNumberTextField.setText("");
			   }
			});
}


	private JLabel recLabel;
	private JTextField recTextField;
	private JLabel lastNameLabel;
	private JTextField lastNameTextField;
	private JLabel firstNameLabel;
	private JTextField firstNameTextField;
	private JLabel phoneNumberLabel;
	private JTextField phoneNumberTextField;
	
	private JTextArea ResultsDisplay;
	
	//All buttons
	private JButton addButton;
	private JButton updateButton;
	private JButton findButton;
	private JButton deleteButton;
	private JButton clearButton;
	private JButton exitButton;
	
	//All Panels
	private JPanel entryPanel;
	private JPanel buttonPanel;
	
	private Contact currentEntry;
	private Queries contactQueries;
	//private int numberofEntries;
}
		

	


